package edu.xidian.sselab.cloudcourse.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component //将这个类注册到Spring容器中
public class HbaseClient { //用来建立和Hbase数据库的连接

    private Configuration configuration; //配置连接的属性
    private Connection connection; //连接实例类

    @Autowired
    //在方法上标注@Autowired注解，使用这个注解之后Spring容器创建当前对象的时候就会调用这个方法，完成赋值。
    public HbaseClient() {
        configuration = new Configuration();
        configuration.set("hbase.zookeeper.quorum", "wbj:2181,lh:2181"); //配置集群ip和端口
        configuration.set("hbase.rpc.timeout", "3600000");
        configuration.set("hbase.client.operation.timeout", "36000000");
    }

    //建立连接
    public Connection getConnection() {
        if (connection == null || connection.isClosed()) {
            try {
                connection = ConnectionFactory.createConnection(configuration); //注入配置，创建连接
            } catch (IOException e) {
                System.out.println("HBase数据库连接关闭，尝试重新连接失败!");
                e.printStackTrace();
            }
        }
        return connection;//初始化Connection类对象，并返回
    }

    public Table getTableByName(String tableName) {
        try {
            return connection.getTable(TableName.valueOf(tableName)); //根据表的名字获取对特定表的连接
        } catch (IOException e) {
            System.out.println("连接数据库表失败!");
            e.printStackTrace();
        }
        return null;
    }

    public void closeConnection(){
        if (connection!=null && !connection.isClosed()){
            try{
                connection.close();
            } catch (IOException e) {
                System.out.println("关闭HBase数据库连接失败！");
                e.printStackTrace();
            }
        }
    }
    
}
